package com.siyoumi.app.sys.entity;

import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.entity.SysAccsuperConfig;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.XAes;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * aes加解密，参数
 */
@Data
@Slf4j
public class AesKi {
    String key;
    String iv;

    static public AesKi ofByConfig() {
        SysAccsuperConfig entityConfig = XHttpContext.getXConfig();
        return of(entityConfig.getAconfig_token());
    }

    static public AesKi of(String token) {
        if (token.length() < 24) {
            XValidator.err(EnumSys.ERR_VAL.getR("token小于24长度"));
        }

        AesKi data = new AesKi();
        data.setKey(token.substring(0, 24));
        data.setIv(token.substring(token.length() - 16));

        return data;
    }

    public String encTxt(String text) {
        if (XStr.isNullOrEmpty(text)) {
            return text;
        }

        try {
            return XAes.encrypt(text, getKey(), getIv());
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public String decTxt(String encTxt) {
        return decTxt(encTxt, true);
    }

    public String decTxt(String encTxt, Boolean throwEx) {
        if (XStr.isNullOrEmpty(encTxt)) {
            return encTxt;
        }

        try {
            return XAes.decrypt(encTxt, getKey(), getIv());
        } catch (Exception e) {
            log.error(e.getMessage());
            log.info("key: {}，iv: {}", getKey(), getIv());
            if (throwEx) {
                XReturn r = EnumSys.ERR_VAL.getR("解密失败");
                r.setData("enc_text", encTxt);
                XValidator.err(r);
            }
        }

        return null;
    }
}
